<?php

	//header("Content-type: text");
	
	session_start();
	
	require "Twitter/index.php";
// Get PageIdx / PageNum / Search Key
	$xml = simplexml_load_file('php://input');
    //$xml = simplexml_load_file('StreamA.xml');
	
	foreach( $xml->attributes( ) as $attr)
	{
		$AttrArray[] = $attr;
	}
	
	$nMaxNum = $AttrArray[0];
	$nPageIdx= $AttrArray[1];
	$nItemIdx = ($nPageIdx - 1) * $nMaxNum;
	$strCategory = $AttrArray[2];
	$strColor = $AttrArray[3];
	$strTag = $AttrArray[4];
	$nLocation = $AttrArray[5];
	
	// Get Organization User account
	$Access_token = "744201864-agn4IQ8yJ3O6CKa2NhbNca7Ow6UvWAJC9SgqEPZG";
	$Access_token_secret = "Q5FNaKwH3HtTkHy34lbOQOnuosbD0cNgnRR1ptglo0E";
	
//	if( isset($_POST['XMLidx']))
//	{
//		$nItemIdx = ($_POST['XMLidx'] - 1) * $nMaxNum;
//	}

// if PageIdx = 1 
	if( $nItemIdx == 0 )
	{
		session_unset ( );
		// Get Each queue = getItem( 0, PageNum )
		$_SESSION['QBeSpoke'] = GetDataFromSQL( $nItemIdx, $nMaxNum, $strCategory, $strColor, $strTag, $nLocation );
		$_SESSION['QFacebook'] = array();
		$_SESSION['QTwitter'] = GetTwitterMedia( Array("twitter_count"=>$nMaxNum,'Access_token'=>$Access_token,'Access_token_secret'=>$Access_token_secret,'Reset'=>'true'));//file_get_contents('http://107.22.182.14/BeSpokeAPI/Twitter/index.php?twitter_count='.$nMaxNum.'&Access_token='.$Access_token.'&Access_token_secret='.$Access_token.'&Reset=true');
		//$_SESSION['QTwitter'] = include 'http://107.22.182.14/BeSpokeAPI/Twitter/index.php?twitter_count='.$nMaxNum.'&Access_token='.$Access_token.'&Access_token_secret='.$Access_token.'&Reset=true';
		$_SESSION['QTumblr'] = array();
		$_SESSION['QInstantgram'] = array();
		// each QEnd = PageNum
		$_SESSION['QEnd'] = array( "BeSpoke"=>$nMaxNum+1, "Facebook"=>$nMaxNum+1, "Twitter"=>$nMaxNum+1, "Tumblr"=>$nMaxNum+1, "Instantgram"=>$nMaxNum+1 );
	}
// else 
	else
	{
	// if each QLength < PageNum
		//queue += getItem( QEnd, PageNum )
		//QEnd += PageNum
		if( count($_SESSION['QBeSpoke']) < $nMaxNum)
		{
			$_SESSION['QBeSpoke'] = array_merge($_SESSION['QBeSpoke'], GetDataFromSQL( $_SESSION['QEnd']['BeSpoke'], $nMaxNum, $strCategory, $strColor, $strTag, $nLocation ));
			$_SESSION['QEnd']['BeSpoke'] += $nMaxNum;
		}		
		if( count($_SESSION['QTwitter']) < $nMaxNum)
		{
			$_SESSION['QTwitter'] = array_merge($_SESSION['QTwitter'],GetTwitterMedia( Array("twitter_count"=>$nMaxNum,'Access_token'=>$Access_token,'Access_token_secret'=>$Access_token_secret,'Reset'=>'false')));
			$_SESSION['QEnd']['Twitter'] += $nMaxNum;
		}		
	}
	
	// Check is Query Empty
	/*
	if( $_SESSION['QEnd']['BeSpoke'] != -1 && count($_SESSION['QBeSpoke']) < $nMaxNum)
		$_SESSION['QEnd']['BeSpoke'] = -1;
	if( $_SESSION['QEnd']['Facebook'] != -1 && count($_SESSION['QFacebook']) < $nMaxNum)
		$_SESSION['QEnd']['Facebook'] = -1;
	if( $_SESSION['QEnd']['Twitter'] != -1 && count($_SESSION['QTwitter']) < $nMaxNum)
		$_SESSION['QEnd']['Twitter'] = -1;
	if( $_SESSION['QEnd']['Tumblr'] != -1 && count($_SESSION['QTumblr']) < $nMaxNum)
		$_SESSION['QEnd']['Tumblr'] = -1;
	if( $_SESSION['QEnd']['Instantgram'] != -1 && count($_SESSION['QInstantgram']) < $nMaxNum)
		$_SESSION['QEnd']['Instantgram'] = -1;
	*/
	// End of Check Empty
	
	echo '<MediaLists>';		
// pop new (n) Item from queues to Output
	for( $i = 0 ; $i < 20 ; $i++ )
	{
		unset($strKey);
		$Time = 0;
//		Max( $QBeSpoke, $QFacebook, $QTwitter, $QTumblr, $QInstantgram);
		if( !empty($_SESSION['QBeSpoke']) )
		{
			$strKey = 'QBeSpoke';
			$Time = $_SESSION['QBeSpoke'][0][0]['lastUpdate'];
		}
		if( !empty($_SESSION['QFacebook']) && $_SESSION['QFacebook'][0][0]['lastUpdate'] > $Time)
		{
			$strKey = 'QFacebook';
			$Time = $_SESSION['QFacebook'][0][0]['lastUpdate'];
		}
		if( !empty($_SESSION['QTwitter']) && $_SESSION['QTwitter'][0][0]['lastUpdate'] > $Time )
		{
			$strKey = 'QTwitter';
			$Time = $_SESSION['QTwitter'][0][0]['lastUpdate'];
		}
		if( !empty($_SESSION['QTumblr']) && $_SESSION['QTumblr'][0][0]['lastUpdate'] > $Time )
		{
			$strKey = 'QTumblr';
			$Time = $_SESSION['QTumblr'][0][0]['lastUpdate'];
		}
		if( !empty($_SESSION['QInstantgram']) && $_SESSION['QInstantgram'][0][0]['lastUpdate'] > $Time )
		{
			$strKey = 'QInstantgram';
			$Time = $_SESSION['QInstantgram'][0][0]['lastUpdate'];
		}
		if( !isset($strKey) )
		{
			break;
		}
//		$Output = array_shift( $QMax );
		$Output = array_shift( $_SESSION[$strKey] );
		OutputXMLFormat( $Output );
	}
	echo '</MediaLists>';	
	
	function GetDataFromSQL( $start, $num, $Category, $Color, $Tag, $Location )
	{
		$MediaList = array();
    	//Link to MySql
    	include("mysql_connect.php");

		$strSqlCommand = "SELECT MediaDownloadPath FROM Global_Config WHERE 1";
		$result = mysql_query($strSqlCommand);
		$row = @mysql_fetch_array($result);	
		$ServerPath = $row['MediaDownloadPath'];
    
		// Search Media Table with 4 Tables' Name
    	$strSqlCommand = "SELECT idMEDIA, MEDIA_TYPE_idMEDIA_TYPE, WebLink, ModifyTime 
						FROM MEDIA tbMed
						LEFT JOIN CATEGORY tbCat	ON tbCat.idCATEGORY = tbMed.CATEGORY_idCATEGORY
						LEFT JOIN COLOR tbCol		ON tbCol.idCOLOR = tbMed.COLOR_idCOLOR
						LEFT JOIN TAGS tbTag		ON tbTag.idTAGS = tbMed.TAGS_idTAGS
						LEFT JOIN LOCATION tbLoc	ON tbMed.LOCATION_idLOCATION = tbLoc.idLOCATION
						LEFT JOIN ZIPCODE tbZip 	ON tbLoc.ZIPCODE_idZIPCODE = tbZip.idZIPCODE ";
    
		if( strlen($Category) > 0 )
			$strSqlCommand .= "AND tbCat.Name = '$Category' ";
	
		if( strlen($Color) > 0 )
			$strSqlCommand .= "AND tbCol.Name = '$Color' ";
	
		if( strlen($Tag) > 0 )
			$strSqlCommand .= "AND tbTag.Name = '$Tag' ";
	
		if( $Location > 0 )
			$strSqlCommand .= "AND tbZip.ZipCode = '$Location' ";
    
		$strSqlCommand .= "LIMIT $start, $num ";
    
		// Get Media Item List
		$result = mysql_query($strSqlCommand);

		while($rowMedia = @mysql_fetch_array($result))	
		{
			$Media = array();
			
			// Get Comment Count
			$nID = $rowMedia['idMEDIA'];
			$strSqlCommand = "SELECT * FROM COMMENTS WHERE MEDIA_idMEDIA = '$nID'";
			$resultComment = mysql_query($strSqlCommand);	
			$nCommentCount = @mysql_num_rows($resultComment);
        
			// Get Media Type
			$nTypeID = $rowMedia['MEDIA_TYPE_idMEDIA_TYPE'];
			$strSqlCommand = "SELECT Name FROM MEDIA_TYPE WHERE idMEDIA_TYPE = '$nTypeID'";
			$resultMediaType = mysql_query($strSqlCommand);	
			$rowMediaType = @mysql_fetch_array($resultMediaType);
		
			$MediaDetial = array( "Head"=>"Media", "ID"=>$nID, "MediaType"=>$rowMediaType['Name'], "CommentCount"=>$nCommentCount, 
			"WebLink"=>$rowMedia['WebLink'], "Source"=>"BeSpoke", "Author"=>"" ,"lastUpdate"=>$rowMedia['ModifyTime']);
			array_push( $Media, $MediaDetial );

			// Get Text Data
			$strSqlCommand = "SELECT * FROM TEXT WHERE MEDIA_idMEDIA = '$nID'";
			$resultText = mysql_query($strSqlCommand);	
			while($rowText = mysql_fetch_array($resultText))
			{
				$MediaDetial = array( "Head"=>"Text", "ID"=>$rowText['idText'], "Title"=>$rowText['Title'], "Description"=>$rowText['Description']);
				array_push( $Media, $MediaDetial );
			}
		
			// Get Image Data
			$strSqlCommand = "SELECT * FROM IMAGE WHERE MEDIA_idMEDIA = '$nID'";
			$resultImage = mysql_query($strSqlCommand);	
			while($rowImage = mysql_fetch_array($resultImage))
			{
				$MediaDetial = array( "Head"=>"Image", "ID"=>$rowImage['idIMAGE'], "Type"=>$rowImage['Type'],
				 "FileName"=>$ServerPath.$nID."/".$rowImage['FileName'], "Description"=>"");
				array_push( $Media, $MediaDetial );
			}
		
			// Get Video Data
			$strSqlCommand = "SELECT * FROM Video WHERE MEDIA_idMEDIA = '$nID'";
			$resultVideo = mysql_query($strSqlCommand);	
			while($rowVideo = mysql_fetch_array($resultVideo))
			{
				$MediaDetial = array( "Head"=>"Video", "ID"=>$rowVideo['idVideo'], "Type"=>$rowVideo['Type'],
				 "FileName"=>$ServerPath.$nID."/".$rowVideo['FileName'], "Description"=>"");
				array_push( $Media, $MediaDetial );
			}
		
			array_push ($MediaList, $Media);
    	}
		
		return $MediaList;
	}
	
	function OutputXMLFormat( $OutputData )
	{
		foreach( $OutputData as $OutputRow)
		{
			switch($OutputRow['Head'])
			{
				case "Media":
					echo '<Media ID="'.$OutputRow['ID'].'" MediaType="'.$OutputRow['MediaType'].'" CommentCount="'.$OutputRow['CommentCount'].
					'" WebLink="'.$OutputRow['WebLink'].'" Source="Twitter" Author="'.$OutputRow['Author'].'" lastUpdate="'.date("Y-m-d",strtotime($OutputRow['lastUpdate'])).'" >';
					break;
				case "Text":
					echo '<Text ID="'.$OutputRow['ID'].'" Title="'.XMLCharEncode($OutputRow['Title']).'" Description="'.XMLCharEncode($OutputRow['Description']).'" />';
					break;
				case "Image":
					echo '<Image ID="'.$OutputRow['ID'].'" Type="'.$OutputRow['Type'].'" FileName="'.$OutputRow['FileName'].'" Description="'.XMLCharEncode($OutputRow['Description']).'" />';
					break;
				case "Video":
					echo '<Video ID="'.$OutputRow['ID'].'" Type="'.$OutputRow['Type'].'" FileName="'.$OutputRow['FileName'].'" Description="'.XMLCharEncode($OutputRow['Description']).'" />';
					break;
			}
		}
		echo '</Media>';
	}
	
	function XMLCharEncode( $Subject )
	{
		$Serach  = array( "<", ">", "&", "'","\"" );
		$Replace = array( "&lt;","&gt;","&amp;","&apos;","&quot;");
		return str_replace($Serach, $Replace, $Subject);
	}
	
	
	
?>